#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from lj_tool import tool_cache, tool_json, tool_server
from . import action_data

orm_ai_server = action_data.init_action_data(
    "ai_server", "272ab1b9c5cc4ea2b76302238247284c")
orm_vision_model = action_data.init_action_data(
    "ai_vision_model", "272ab1b9c5cc4ea2b76302238247284c")

orm_device_config = action_data.init_action_data("things_device_config")


def is_ai_camera(camera):
    if not camera:
        return False
    config = tool_json.lj_json_loads(camera.config)
    if not config or not config.get("ai-vision"):
        return False
    is_open = tool_json.lj_json_loads(config.get("ai-vision")).get("open")
    if is_open == "true" or is_open == True:
        return True
    return False


def transform_camera(camera):
    config = tool_json.lj_json_loads(camera.config)
    config_ai_vision = tool_json.lj_json_loads(config.get("ai-vision"))
    return {
        "code": camera.code,
        "models": config_ai_vision and config_ai_vision.get("open_models")
    }


@tool_cache.lj_wrapper_cache(key="action_ai_list_ai_server", expiration_seconds=60 * 5)
def list_ai_server():
    return orm_ai_server.list()


@tool_cache.lj_wrapper_cache(key="action_ai_list_ai_analysis_server", expiration_seconds=60 * 5)
def list_ai_analysis_server():
    # 过滤掉分析流不能连接的服务，保留可以正常连接分析的
    return [item for item in orm_ai_server.list() if tool_server.test_port(item.uri, item.analysis_port)]


@tool_cache.lj_wrapper_cache(key="action_ai_list_camera", expiration_seconds=60 * 5)
def list_camera():
    camera_list = orm_device_config.list()
    return [transform_camera(camera) for camera in camera_list if is_ai_camera(camera)]


@tool_cache.lj_wrapper_cache(key="action_ai_list_model", expiration_seconds=60 * 5)
def list_model():
    return orm_vision_model.list()


@tool_cache.lj_wrapper_cache(key="action_ai_get_model_by_code", expiration_seconds=60 * 5)
def get_model_by_code(code):
    model_entity = orm_vision_model.entity
    return model_entity.get(model_entity.code == code)
